<template>
    <div>
        <!-- 面包屑导航区域 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片区域 -->
        <el-card>
            <!-- 添加角色按钮区域 -->
            <el-row :gutter="20">
                 <el-col :span="4">
                    <el-button type="primary" @click="addDialogVisible = true">添加角色</el-button>
                </el-col>
            </el-row>
            
            <!-- 添加角色 -->
            <el-dialog
            title="添加角色"
            :visible.sync="addDialogVisible"
            @close="addFormReset"
            width="50%">
                <!-- 主体添加角色内容 -->
                <el-form
                :model="addForm"
                :rules="addFormRules" 
                ref="addFormRef"  
                label-width="100px">
                    <el-form-item label="角色名称" prop="roleName">
                        <el-input v-model="addForm.roleName"></el-input>
                    </el-form-item>
                     <el-form-item label="角色描述" prop="roleDesc">    
                        <el-input v-model="addForm.roleDesc"></el-input>
                    </el-form-item>
                </el-form>
                <!-- 底部按钮 -->
                <span slot="footer">
                    <el-button @click="addDialogVisible = false" resetField>取 消</el-button>
                    <el-button type="primary" @click="addUser">确 定</el-button>
                </span>
            </el-dialog>

            <!-- 编辑修改角色 -->
            <el-dialog
            title="修改角色信息"
            :visible.sync="editDialogVisible"
            width="30%">
                <!-- 主体添加角色内容 -->
                <el-form
                :model="editForm"
                :rules="editFormRules" 
                ref="editFormRef"  
                label-width="100px">
                    <el-form-item label="角色名称" prop="roleName">
                        <el-input v-model="editForm.roleName"></el-input>
                    </el-form-item>
                     <el-form-item label="角色描述" prop="roleDesc">    
                        <el-input v-model="editForm.roleDesc"></el-input>
                    </el-form-item>
                </el-form>
                <!-- 底部按钮区域 -->
                <span slot="footer" class="dialog-footer">
                    <el-button @click="editDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="editUserInfo">确 定</el-button>
                </span>
            </el-dialog>
           
            <!-- 角色列表区域 -->
            <el-table :data="rolelist" border stripe>
                <!-- 展开列 -->
                <el-table-column type="expand">
                    <template slot-scope="scope">
                        <el-row :class="['dbbottom',i === 0 ? 'dbtop':'','venter']" v-for="(item1,i) in scope.row.children" :key="i">
                            <!-- 一级区域 -->
                            <el-col :span="5" >
                                <el-tag closable type="primary">{{item1.authName}}</el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <!-- 二三级区域 -->
                            <el-col :span="19">
                                <el-row :class="[i === 0 ? '':'dbtop','venter']" v-for="(item2,i) in item1.children" :key="i">
                                    <!-- 二级权限区域 -->
                                    <el-col :span="6">
                                        <el-tag closable type="success">{{item2.authName}}</el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <!-- 三级权限区域 -->
                                    <el-col :span="13">
                                        <el-tag closable type="warning" v-for="(item3,i) in item2.children" :key="i" @close="removeRightTag(scope.row.id,item3.id)">{{item3.authName}}</el-tag>
                                    </el-col>
                                </el-row>
                            </el-col>
                       </el-row>
                    </template>
                </el-table-column>
                <!-- 索引列 -->
                <el-table-column type="index"></el-table-column>
                <el-table-column label="角色名称" prop="roleName" ></el-table-column>
                <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                         <!-- 编辑按钮 -->
                        <el-button type="primary" icon="el-icon-edit" size="mini" @click="editDialog(scope.row.id)">编辑</el-button>
                        <!-- 删除按钮 -->
                        <el-button type="danger" 
                        icon="el-icon-delete"
                        @click="removeUserById(scope.row.id)" 
                        size="mini">删除</el-button>
                        <!-- 分配权限按钮 -->
                           <el-button 
                           type="warning" 
                           icon="el-icon-setting"
                           @click="showSetRightDialog(scope.row)" 
                           size="mini">分配权限</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 权限分配对话框 -->
            <el-dialog
            title="分配权限"
            :visible.sync="SetDialogVisible"
            @close="showSetRightDialogClosed"
            width="50%">
                <!-- 主体添加角色内容 -->
                <el-tree 
                :data="rightslist"
                show-checkbox
                node-key="id"
                default-expand-all
                ref="treeRef"
                :default-checked-keys="defKeys" 
                :props="treeProps"></el-tree>
                <!-- 底部按钮 -->
                <span slot="footer">
                    <el-button @click="SetDialogVisible = false" resetField>取 消</el-button>
                    <el-button type="primary" @click="allotRights">确 定</el-button>
                </span>
            </el-dialog>
        </el-card>
    </div>
</template>

<script>
export default {
    data() {
        return {
            // 所有角色列表数据
            rolelist: [],
            // 控制添加角色的显示与隐藏
            addDialogVisible: false,
            // 添加角色
            addForm: {
                roleName: '',
                roleDesc: ''
            },
            // 添加角色条件
            addFormRules: {
                roleName: [
                    {
                        required: true,
                        message: '请输入角色名称', 
                        trigger: 'blur' 
                    },
                    { 
                        min: 1, 
                        max: 10, 
                        message: '长度在 1 到 10 个字符', 
                        trigger: 'blur' 
                    }
                ],
                roleDesc: [
                    {
                        required: true,
                        message: '请输入角色描述', 
                        trigger: 'blur' 
                    },
                    { 
                        min: 1, 
                        max: 15, 
                        message: '长度在 1 到 15 个字符', 
                        trigger: 'blur' 
                    }
                ]
            },
            // 修改角色信息框显示与隐藏
            editDialogVisible: false,
            // 和获取对应的用户信息
            editForm: {},
            editFormRules: {
                roleName: [
                    {
                        required: true,
                        message: '请输入角色名称', 
                        trigger: 'blur' 
                    },
                    { 
                        min: 1, 
                        max: 10, 
                        message: '长度在 1 到 10 个字符', 
                        trigger: 'blur' 
                    }
                ],
                roleDesc: [
                    {
                        required: true,
                        message: '请输入角色描述', 
                        trigger: 'blur' 
                    },
                    { 
                        min: 1, 
                        max: 15, 
                        message: '长度在 1 到 15 个字符', 
                        trigger: 'blur' 
                    }
                ]
            },
            // 分配权限显示与隐藏
            SetDialogVisible: false,
            // 分配权限信息
            rightslist: [],
            // 树形结构展示
            treeProps: {
                label: 'authName',
                children: 'children'
            },
            // 默认选中节点ID值数组
            defKeys: [],
            // 当前即将分配权限的角色ID
            roleId : ''
        }
    },
    created() {
        this.getRolesList()
    },
    methods: {
        async getRolesList() {
            const {data: res} = await this.$http.get('roles')
            console.log(res);
            if(res.meta.status != 200) {
                return this.$message.error("获取角色列表权限失败")
            }
            this.rolelist = res.data
            console.log("获取成功");
        },
        // 对添加表单进行校验
         addUser() {
            this.$refs.addFormRef.validate(async valid => {
                if(!valid) return 

                const {data: res}= await this.$http.post('roles',this.addForm)
                if(res.meta.status != 201) {
                    return this.$message.error("添加角色失败")
                }
                // 隐藏添加角色框
                this.addDialogVisible = false
                // 
                this.getRolesList()
                this.$message.success("添加角色成功")
            })
        },
        // 对表单进行重置
        addFormReset() {
            this.$refs.addFormRef.resetFields()
        },
        // 修改角色信息表单校验
        async editDialog(id) {
            // 显示表单框
            this.editDialogVisible = true

            const {data: res} = await this.$http.get(`roles/` + id)
            if(res.meta.status !== 200) return this.$message.error("检验失败")
            this.editForm = res.data
        },
        // 修改角色信息并提交
        editUserInfo() {
            this.$refs.editFormRef.validate( async valid => {
                if( !valid) return
                const {data: res} = await this.$http.put(`roles/` + this.editForm.roleId,{
                    roleName: this.editForm.roleName,
                    roleDesc: this.editForm.roleDesc
                })
                console.log(res);
                if(res.meta.status !== 200) return this.$message.error("修改角色信息失败")

                // 关闭修改用户对话框
                this.editDialogVisible = false
                // 更新数据
                this.getRolesList()
                // 提示修改用户信息成功
                this.$message.success("修改用户信息成功")
            })
        },
        // 删除角色信息
        async removeUserById(id) {
            // 异步函数
            const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
            }).catch(err => err)  // catch  点击取消的时候如果有错误，返回错误
            console.log(confirmResult);

            // 点击确认时返回字符串 confirm
            // 点击取消时返回字符串 cancel

            if(confirmResult !== 'confirm') return 

            const {data: res} = await this.$http.delete(`roles/` + id)
            if(res.meta.status != 200){
                return this.$message.error("删除失败")
            }
            // 重新加载角色信息
            this.getRolesList()

            this.$message.success("删除成功")

            
        },
        // 删除ID对应权限
        async removeRightTag(id1,id2) {
            const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
            }).catch(err => err)

            if(confirmResult != 'confirm') return 

            const {data: res} = await this.$http.delete(`roles/${id1}/rights/${id2}`)
            if(res.meta.status != 200) return this.$message.error("删除权限失败")
            
            // 重新加载角色信息
            this.getRolesList()

            this.$message.success("删除角色权限成功") 
        },
        // 展示分配权限对话框
        async showSetRightDialog(role) {
            this.roleId = role.id
            const {data: res} = await this.$http.get('rights/tree')
            if(res.meta.status !== 200) return this.$message.error("获取权限列表失败")
            this.rightslist = res.data
            console.log(this.rightslist)

             // 调用递归方法获取三级节点ID
            this.getLeafKeys(role,this.defKeys)


            // 权限对话框的显示
            this.SetDialogVisible = true
        },
        // 通过递归的形式，获取角色下所有三级权限的id，并保存到defKeys数组中
        getLeafKeys(node, arr) {
            // 如果当前node节点不包含children属性，则是三级节点
            if(!node.children) {
                return arr.push(node.id)
            }

            // 如果不是三级的权限进行递归
            node.children.forEach(item => 
              this.getLeafKeys(item, arr)
            )
        },
        // 监听分配权限对话框关闭事件
        showSetRightDialogClosed() {
            this.defKeys = []
        },
        // 为角色分配权限
        async allotRights() {
            const keys = [
                ...this.$refs.treeRef.getCheckedKeys(),
                ...this.$refs.treeRef.getHalfCheckedKeys()
            ]

            const idStr = keys.join(',')

            const {data: res} = await this.$http.post(`roles/${this.roleId}/rights`,{rids: idStr})
            if(res.meta.status !== 200) {
                return this.$message.error("角色分配权限失败")
            }
            this.$message.success("角色分配权限成功")
            this.getRolesList()
            this.SetDialogVisible = false
        }
    },
}
</script>

<style lang="less" scoped>
.dbtop{
    border-top: 1px solid rgb(184, 182, 182);
}

.dbbottom{
    border-bottom: 1px solid rgb(184, 182, 182);
}
.el-tag{
    margin: 10px;
}

.venter{
    display: flex;
    align-items: center;
}
</style>